/*
 * (c) Copyright 2009 Hewlett-Packard Development Company, LP
 * All rights reserved.
 * [See end of file]
 */

package com.hp.hpl.jena.clusteredtdb.comms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

import com.hp.hpl.jena.clusteredtdb.base.UtilityFunctions;

public class RemoteServer {
	HostnameAndPort hap;
	int serverId;
	HashMap<Integer,RemoteVNode> vns;
	SocketPool sockets;
	//Socket vnsocket;
	PrintWriter out = null;
	BufferedReader in = null;
	
	
	public RemoteServer(String hostname, int port, int serverId, int maxConns) {
		this.serverId = serverId;
		this.hap = new HostnameAndPort(hostname, port);
		vns = new HashMap<Integer,RemoteVNode>();
		sockets = new SocketPool(maxConns, hap);
	}
	
	public void init() {
//		create a socket, along with readers and writers.
	/*	try {
			vnsocket = new Socket(hap.hostname, hap.port);
			out = new PrintWriter(vnsocket.getOutputStream());
			in = new BufferedReader(new InputStreamReader(vnsocket.getInputStream()));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}*/
	}
	
	public void addVNode(RemoteVNode vn) {
		this.vns.put(new Integer(vn.getId()), vn);
	}
	
	public RemoteVNode getVNode(int id) {
		return vns.get(new Integer(id));
	}
	
	public Collection<RemoteVNode> getVNodes() {
		return vns.values();
	}
	
	public HashMap<Integer,RemoteVNode> getVNodeMap() {
		return vns;
	}
	
	/*
	 * Send request to specified vnodes on this server.  Could do some error checking on
	 * the passed vnode ids here?
	 */
	public ResponseProcessor queryVNodes(int[] vnodeIds, ArrayList<String> request, ResponseProcessor rp) {
		return this.sendSimpleRequest(vnodeIds, request, rp);
	}
	
	public ResponseProcessor queryServer(ArrayList<String> request, ResponseProcessor rp) {
		int[] vnodeIds = {-1}; // -1 = all nodes
		return this.sendSimpleRequest(vnodeIds, request, rp);
	}
	
	/*
	 * Performs a simple noninteractive send/receive to the VNode.
	 */
	public ResponseProcessor sendSimpleRequest(int[] vnodeIds, ArrayList<String> request, ResponseProcessor rp) {
		
		
		String fromServer;
		ReadWriteSocket vnsocket;
		try {
			
			//if(this.vnsocket == null || this.vnsocket.isClosed()) {
			//	init();
			//}
			vnsocket = this.sockets.getFreeSocket();
			PrintWriter sout = vnsocket.getOut();
			BufferedReader sin = vnsocket.getIn();
			//transmit find request
			sout.println(UtilityFunctions.intArrayToSpacedTupleString(vnodeIds));
			java.util.Iterator<String> reqiterator = request.iterator();
			while (reqiterator.hasNext()) {
				sout.println(reqiterator.next());
			}
			sout.println("END");
			sout.flush();
			
			//read data sent back, process
			while ((fromServer = sin.readLine()) != null) {
				if (fromServer.equals("END"))
			        break;
			   rp.addString(fromServer);
			}
			
			sockets.freeSocket(vnsocket);
			
		} catch (UnknownHostException e) {
			System.out.println("Could not find host: " + hap + " " + e);
			return null;
		} catch (IOException e) {
			System.out.println("I/O Error: " + e);
			return null;
		}
		
		return rp;
		
	}
	
		
}

/*
 * (c) Copyright 2009 Hewlett-Packard Development Company, LP
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
